const express = require('express');
const router = express.Router();
const RecommendService = require('../services/recommendService');

// 初始化推荐服务
router.use((req, res, next) => {
    req.recommendService = new RecommendService(req.neo4j, req.db);
    next();
});

// 记录用户行为
router.post('/action', async (req, res) => {
    try {
        const { goodsId, actionType } = req.body;
        
        // 检查必要参数
        if (!goodsId || !actionType) {
            return res.send({ code: 400, message: '缺少必要参数: goodsId 或 actionType' });
        }
        
        // 确保 actionType 是有效值
        const validActionTypes = ['view', 'collect', 'share'];
        if (!validActionTypes.includes(actionType)) {
            return res.send({ code: 400, message: '无效的 actionType，有效值为: view, collect, share' });
        }
        
        // 检查用户是否已登录
        let userId;
        if (!req.user) {
            // 如果用户未登录，使用临时ID记录（或者返回需要登录的信息）
            // 为了允许未登录用户也能记录行为，这里使用一个固定的访客ID
            userId = 1; // 假设ID 1 是访客用户
            console.log(`未登录用户的行为记录，使用默认访客ID ${userId}`);
        } else {
            // 根据 req.user 的结构获取 userId
            userId = req.user.userId || req.user.id;
            
            if (!userId) {
                console.error('无法获取用户ID，req.user 结构:', req.user);
                return res.send({ code: 400, message: '无法识别的用户身份' });
            }
        }
        
        console.log(`记录用户行为: userId=${userId}, goodsId=${goodsId}, actionType=${actionType}`);
        await req.recommendService.recordUserAction(userId, goodsId, actionType);
        res.send({ code: 200, message: '行为记录成功' });
    } catch (error) {
        console.error('记录用户行为失败:', error);
        res.send({ code: 500, message: `记录用户行为失败: ${error.message || '未知错误'}` });
    }
});

// 获取个性化推荐
router.get('/personalized', async (req, res) => {
    try {
        let userId = null;
        // 检查用户是否已登录
        if (req.user && req.user.id) {
            userId = req.user.id;
        }
        
        let recommendations;
        if (userId) {
            // 如果用户已登录，获取个性化推荐
            recommendations = await req.recommendService.getRecommendations(userId);
        } else {
            // 如果用户未登录，获取热门推荐
            recommendations = await req.recommendService.getPopularItems();
        }
        
        res.send({ code: 200, data: recommendations });
    } catch (error) {
        console.error('获取个性化推荐失败:', error);
        res.send({ code: 500, message: '获取推荐失败', error: error.message });
    }
});

// 获取基于历史背景的推荐
router.get('/historical', async (req, res) => {
    try {
        let userId = null;
        // 检查用户是否已登录
        if (req.user && req.user.id) {
            userId = req.user.id;
        }
        
        let recommendations;
        if (userId) {
            // 如果用户已登录，获取基于历史的个性化推荐
            recommendations = await req.recommendService.getHistoricalRecommendations(userId);
        } else {
            // 如果用户未登录，获取热门历史文化相关商品
            recommendations = await req.recommendService.getHistoricalItems();
        }
        
        res.send({ code: 200, data: recommendations });
    } catch (error) {
        console.error('获取历史推荐失败:', error);
        res.send({ code: 500, message: '获取推荐失败', error: error.message });
    }
});

// 获取商品知识图谱数据（用于可视化）
router.get('/knowledge-graph/:goodsId', async (req, res) => {
    try {
        const { goodsId } = req.params;
        if (!goodsId) {
            return res.send({ code: 400, message: '商品ID不能为空' });
        }
        
        const graphData = await req.recommendService.getKnowledgeGraphData(goodsId);
        res.send({ 
            code: 200, 
            data: graphData,
            message: 'success' 
        });
    } catch (error) {
        console.error('获取知识图谱可视化数据失败:', error);
        res.send({ code: 500, message: '获取知识图谱数据失败' });
    }
});

module.exports = router;